import { Session } from '@/utils/storage';
import { user,systemConfig } from '@/store';
import { encryptSM2 } from '@/utils/util';
import { SM3 } from 'gm-crypto';
const LOCAL_TOKEN_NAME = import.meta.env.VITE_LOCAL_TOKEN_NAME as string;
const VITE_CRYPTO_ENANLED = import.meta.env.VITE_CRYPTO_ENANLED as string;
const VITE_SIGN_ENANLED = import.meta.env.VITE_SIGN_ENANLED as string;
const VITE_APP_ID = import.meta.env.VITE_APP_ID as string;
export function signatureGenerate(config){  
  // 密钥，可以是前后端约定好的某一串，也可以是随机的，动态的。
  let data=config.data;
  if(typeof data === 'string'){
    data=JSON.parse(data);
  }
  let params=config.params;
  if(typeof params === 'string'){
    params=JSON.parse(params);
  }
  if(JSON.parse(VITE_CRYPTO_ENANLED)&&(systemConfig.allApiCrytpo|| config?.headers?.cryptoEnabled==='true'|| config?.headers?.cryptoEnabled===true)){
		let secretKey='';
    if(data&& !('cryptoStr' in data)){
      config.oldData=data;
      data={cryptoStr:encryptSM2(JSON.stringify(data),secretKey)};
      config.data=data;
    }
	if(params&&params.length&&params.length && !('cryptoStr' in params)){
      config.oldParams=params;
      params={cryptoStr:encryptSM2(JSON.stringify(params),secretKey)};
      config.params=params;
    }
  }
  let secret = "" as string|null|undefined;
  const token = Session.get(LOCAL_TOKEN_NAME);
	if (token) {
		secret=user.defaultSM2PrivateKey;
	}else{
    secret=systemConfig.defaultSM2PrivateKey;
  }
  // 时间戳
  let timestamp = new Date().getTime()
  
  // post参数
  let dataStr ="";
  if(params){
    if(params.length){
      let sortParams=sortAescParams(params)
      config.params=sortParams;
      dataStr=JSON.stringify(sortParams);
    }
    
  }
  if(data){
    dataStr = dataStr+JSON.stringify(sortAesc(data));
  }

  // 生成签名
  let str = dataStr + "&secret=" + secret + "&timestamp=" + timestamp ;
  console.log("前端签名完整内容："+str)
  const sign = JSON.parse(VITE_SIGN_ENANLED)?SM3.digest(str,'utf8', 'hex'):''
  console.log("前端签名后："+sign.toUpperCase());
	const dataSign=SM3.digest(config.url+dataStr,'utf8', 'hex')
  return {
    signature: JSON.parse(VITE_SIGN_ENANLED)?sign.toUpperCase():'', // 将签名字母转为大写
    timestamp,
    dataSign:dataSign
  }
}
export function signFileParams(){
  //文件签名，只用应用秘钥进行签名
  let secret = '' as string | null | undefined;
  secret = systemConfig.defaultSM2PrivateKey;
  // 时间戳
  let timestamp = new Date().getTime();
  let appId=VITE_APP_ID
  // 生成签名
  let str ='appId=' + appId+'&secret=' + secret + '&timestamp=' + timestamp;
  console.log('前端签名完整内容：' + str);
  const sign = JSON.parse(VITE_SIGN_ENANLED)? SM3.digest(str, 'utf8', 'hex') : '';
  console.log('前端签名后：' + sign.toUpperCase());
  return {
    signature: JSON.parse(VITE_SIGN_ENANLED) ? sign.toUpperCase() : '', // 将签名字母转为大写
    timestamp,
    appId
  };
}
export function getFileSignParams(){
  const {signature, timestamp,appId} =signFileParams();
  const token = Session.get(LOCAL_TOKEN_NAME);
  let str='?signature='+signature+'&timestamp='+timestamp+"&appId="+appId;
  if(token){
    str=str+"&accessToken="+token;
  }
  return str;
}
//复杂json的key排序
const sortAesc=(obj)=>{
  const sortObj = {} as any;
  Object.keys(obj).sort().forEach(item=>{
    let itemOjb=obj[item];
    if(itemOjb!=null&&itemOjb!=undefined){
      if(itemOjb instanceof Array){
        let arrChild =[] as any;
        itemOjb.forEach((index:any)=>{
          if(index.constructor === Object){
            let Objarr = sortAesc(index);
            arrChild.push(Objarr);
          }else{
            arrChild.push(index);
          }
        });
        sortObj[item] = arrChild;
      }else if(itemOjb.constructor === Object){
        if(itemOjb!=null&&itemOjb!=undefined){
          sortObj[item] = sortAesc(itemOjb);
        }
      }else{
        sortObj[item] = itemOjb;
      }
    }
    
  })
  return sortObj;
}

const sortAescParams=(obj)=>{
  const sortObj = {} as any;
  Object.keys(obj).sort().forEach(item=>{
    let itemOjb=obj[item];
    if(itemOjb!=null&&itemOjb!=undefined){
      if(typeof itemOjb=='string'){
        sortObj[item] =itemOjb
      }else{
        sortObj[item] = JSON.stringify(itemOjb);
      }
    }
    
  })
  return sortObj;
}
